from rest_framework import serializers


from goods.models import GoodsCategory,Goods,GoodsImage


# 三级商品分类序列化器
class CategorySerializer3(serializers.ModelSerializer):
    class Meta:
        model = GoodsCategory
        fields = '__all__'

# 二级商品分类序列化器
class CategorySerializer2(serializers.ModelSerializer):
    sub_cat = CategorySerializer3(many=True)
    class Meta:
        model = GoodsCategory
        fields = '__all__'

# 一级商品分类序列化器
class CategorySerializer(serializers.ModelSerializer):
    sub_cat = CategorySerializer2(many=True)
    class Meta:
        model = GoodsCategory
        fields = '__all__'


class GoodsImageSerializer(serializers.ModelSerializer):
    class Meta:
        model = GoodsImage
        fields = ('image',)



# 商品列表页序列化器
class GoodsSerializer(serializers.ModelSerializer):
    # 因为category是Goods的外键，所以需要覆盖外键字段，嵌套序列化。
    category = CategorySerializer()
    #images是数据库中设置的related_name="images"
    images = GoodsImageSerializer(many=True)
    class Meta:
        model = Goods
        fields = '__all__'